package com.github.hgkmail.hello.leetcode101.greedy;

import java.util.Arrays;
import java.util.Comparator;

public class LC435NonOverlappingIntervals {

    public int eraseOverlapIntervals(int[][] intervals) {
        //base case
        if (intervals.length<=0) {
            return 0;
        }
        //把区间列表按区间结尾排序，优先保留区间结尾小的且不与前一个区间重叠的
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1]-o2[1];
            }
        });
        //将与将一个区间重叠的移除
        int eraseNum=0;
        int cur=intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0]<cur) {
                eraseNum+=1;
            } else {
                cur=intervals[i][1];
            }
        }

        return eraseNum;
    }

    public static void main(String[] args) {

    }

}
